package recorder

import (
	"fmt"
	"sync"
	"time"
)

type Manager struct {
	mu           sync.Mutex
	scenes       map[string]*Scene
	nextSceneSeq int
	done         chan struct{}
	outDir       string
}

func NewManager(outDir string) *Manager {
	mgr := &Manager{
		scenes:       make(map[string]*Scene),
		nextSceneSeq: 0,
		done:         make(chan struct{}),
		outDir:       outDir,
	}

	return mgr
}

func (m *Manager) Run() {
	m.handleTimeout()
}

func (m *Manager) newSceneId() string {
	id := fmt.Sprintf("%s-%09d", time.Now().Format("20060102150304"), m.nextSceneSeq)
	m.nextSceneSeq += 1
	if m.nextSceneSeq >= 1000000000 {
		m.nextSceneSeq = 0
	}

	return id
}

func (m *Manager) Close() {
	close(m.done)
}

func (m *Manager) AddScene(scene *Scene) string {
	m.mu.Lock()
	id := m.newSceneId()
	scene.SetId(id)
	m.scenes[id] = scene
	m.mu.Unlock()
	return id
}

func (m *Manager) DelScene(sceneId string) *Scene {
	var scene *Scene
	m.mu.Lock()
	scene, ok := m.scenes[sceneId]
	if ok {
		delete(m.scenes, sceneId)
	}
	m.mu.Unlock()
	return scene
}

func (m *Manager) GetScene(sceneId string) *Scene {
	m.mu.Lock()
	defer m.mu.Unlock()
	scene := m.scenes[sceneId]
	return scene
}

func (m *Manager) handleTimeout() {
	t := time.NewTicker(time.Second * 30)
	for {
		select {
		case <-m.done:
			m.mu.Lock()
			for sceneId, scene := range m.scenes {
				delete(m.scenes, sceneId)
				scene.CreateJobFile(m.outDir)
			}
			m.mu.Unlock()
			return
		case <-t.C:
			// m.mu.Lock()
			// for sceneId, scene := range m.scenes {
			// 	if !scene.IsLive() {
			// 		delete(m.scenes, sceneId)
			// 		log.Infof("scene '%s' closed", sceneId)
			// 		scene.CreateJobFile(m.outDir)
			// 	} else {
			// 		log.Infof("scene '%s' live", sceneId)
			// 	}
			// }
			// m.mu.Unlock()
		}
	}
}
